<template>
  <div class="product">
    <div class="steps">
      <el-steps :active="index" align-center finish-status="success">
        <el-step title="商品基本信息" />
        <el-step title="添加库存信息" />
        <el-step title="添加移动端详情" />
      </el-steps>
    </div>
    <div class="form margin_30">
      <el-form :model="productInfo" label-width="auto" size="small">
        <div v-if="index == 1" class="margin_3''">
          <p class="title">基本属性</p>
          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品名称">
                <el-input v-model="productInfo.product.name" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品编码">
                <el-input v-model="productInfo.product.id" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品分类">
                <el-select v-model="productInfo.product.productCategoryId" style="width:100%" placeholder="请选择" @change="getCategoryName">
                  <el-option
                    v-for="item in categoryList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品品牌">
                <el-select v-model="productInfo.product.brandId" style="width:100%" placeholder="请选择活动区域" @change="getBrandName(productInfo.product.brandId)">
                  <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="16" :offset="0">
              <el-form-item label="商品描述">
                <el-input
                  v-model="productInfo.product.description"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <p class="title">商品属性</p>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品原价">
                <el-input-number v-model="productInfo.product.originalPrice" style="width:100%" label="描述文字" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="促销类型">
                <el-select v-model="productInfo.product.promotionType" style="width:100%" placeholder="请选择" :disabled="true">
                  <el-option label="没有促销使用原价" value="''" />
                  <el-option label="使用促销价" value="1" />
                  <el-option label="使用会员价" value="2" />
                  <el-option label="使用阶梯价格" value="3" />
                  <el-option label="使用满减价格" value="4" />
                  <el-option label="限时购" value="5" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="活动价格">
                <el-input-number v-model="productInfo.product.promotionPrice " style="width:100%" label="描述文字" :disabled="true" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="重量(kg)">
                <el-input-number v-model="productInfo.product.weight" style="width:100%" label="描述文字" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="审核状态"><el-switch
                v-model="productInfo.product.verifyStatus"
                active-color="#4''9eff"
              />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="是否上架"><el-switch
                v-model="productInfo.product.publishStatus"
                active-color="#4''9eff"
              />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="缩略图">
                <el-upload
                  class="avatar-uploader"
                  action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                  :show-file-list="false"
                  :on-success="upImg"
                  :headers="setToken"
                >
                  <img v-if="productInfo.product.pic" style="width:200px;height:200px" :src="productInfo.product.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </el-form-item>

            </el-col>
          </el-row>

          <p class="title">其他信息</p>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="推荐状态"><el-switch
                v-model="productInfo.product.recommendStatus"
                active-color="#4''9eff"
              />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="新品状态"><el-switch
                v-model="productInfo.product.newStatus"
                active-color="#4''9eff"
              />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="预告商品"><el-switch
                v-model="productInfo.product.previewStatus"
                active-color="#4''9eff"
              />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="搜索关键词">
                <el-input v-model="productInfo.product.keywords" />
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="库存预警">
                <el-input-number v-model="productInfo.product.lowStock" style="width:100%" />
              </el-form-item>

            </el-col>
            <el-col :span="8" :offset="0">
              <el-form-item label="商品排序">
                <el-input-number v-model="productInfo.product.sort" style="width:100%" />
              </el-form-item>

            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="产品服务">
                <template>
                  <el-checkbox-group v-model="checkList" @change="getCheckList">
                    <el-checkbox label="1">无忧退货</el-checkbox>
                    <el-checkbox label="2">快速退款</el-checkbox>
                    <el-checkbox label="3">免费包邮</el-checkbox>
                  </el-checkbox-group>
                </template>
              </el-form-item>
            </el-col>
          </el-row>

        </div>
        <div v-if="index ==2">
          <p class="title">商品SKU信息</p>

          <el-row :gutter="20">
            <el-col :span="8" :offset="0">
              <el-form-item label="标题">
                <el-input v-model="productInfo.product.detailTitle" />
              </el-form-item>
            </el-col>
            <el-col :span="12" :offset="0">
              <el-form-item label="副标题">
                <el-input v-model="productInfo.product.subTitle" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8" :offset="0">
              <el-form-item label="画册图片">
                <el-upload
                  action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :headers="setToken"
                  :on-success="upAlbumPics"
                  :file-list="ImgList"
                >
                  <i class="el-icon-plus" />
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-col>

          </el-row>

          <el-form-item label="sku设置">
            <el-row>
              <el-col :span="18" class="center">
                颜色:
                <div v-for="(item , index) in colorList" :key="item.name">
                  <el-checkbox v-model="item.isSelect">{{ item.name }}</el-checkbox>
                  <el-link type="danger" @click="delSkuColor(index)">删除</el-link>
                </div>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18" class="center">
                大小:
                <div v-for="(item , index) in sizeList" :key="item.name">
                  <el-checkbox v-model="item.isSelect">{{ item.name }}</el-checkbox>
                  <el-link type="danger" @click="delSkuSize(index)">删除</el-link>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12" class="center">
                <el-input v-model.trim="color" placeholder="颜色描述,比如土豪金" />
                <el-button size="mini" @click="addColor">创建颜色选项</el-button>
                <el-input v-model.trim="size" placeholder="大小" />
                <el-button size="mini" @click="addSize">创建大小选项</el-button>
              </el-col>
              <el-col :span="3" :offset="3" class="center">
                <el-button type="primary" size="mini" @click="addSku">生成sku</el-button>
                <el-button type="primary" size="mini" @click="addSkuItem">新增sku</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-table :data="productInfo.pmsSkuStockList" border stripe>
            <el-table-column
              type="index"
              label="#"
              fixed="left"
            />
            <el-table-column
              prop=""
              label="图片"
            >
              <template v-slot="scope">
                <el-upload
                  class="avatar-uploader"
                  action="http://leju.bufan.cloud/lejuAdmin/material/uploadFileOss"
                  :show-file-list="false"
                  :on-success="el=>upSkuImg(scope.$index,el)"
                  :headers="setToken"
                >
                  <img v-if="scope.row.pic" style="width:100px;height:100px" :src="scope.row.pic" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="颜色"
            ><template v-slot="scope">
              <el-input v-model="scope.row.spData[0].value" placeholder="" size="mini" clearable />
            </template></el-table-column>
            <el-table-column
              prop=""
              label="大小"
            ><template v-slot="scope">
              <el-input v-model="scope.row.spData[1].value" placeholder="" size="mini" clearable />
            </template></el-table-column>
            <el-table-column
              prop=""
              label="库存"
            ><template v-slot="scope">
              <el-input v-model="scope.row.stock" oninput="value=value.replace(/[^\d]/g,'')" placeholder="自定义库存" size="mini" clearable />
            </template></el-table-column>
            <el-table-column
              prop=""
              label="预警库存"
            ><template v-slot="scope">
              <el-input v-model="scope.row.lowStock" placeholder="预警库存" size="mini" clearable />
            </template></el-table-column>
            <el-table-column
              prop=""
              label="锁定库存"
            >
              <template v-slot="scope">
                <el-input v-model="scope.row.lockStock" placeholder="锁定库存" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="sku编码"
            >
              <template v-slot="scope">
                <el-input v-model="scope.row.skuCode" placeholder="" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="价格"
            >
              <template v-slot="scope">
                <el-input v-model="scope.row.price" placeholder="" size="mini" clearable />
              </template></el-table-column>
            <el-table-column
              prop=""
              label="销量"
            >
              <template v-slot="scope">
                <el-input v-model="scope.row.sale" placeholder="" size="mini" clearable />
              </template>
            </el-table-column>
            <el-table-column
              prop=""
              label="操作"
            >
              <template v-slot="scope">
                <el-link type="danger" :underline="false" target="_blank" @click="delItem(scope.$index)">删除</el-link>

              </template>
            </el-table-column>
          </el-table>

        </div>
        <div v-if="index == 3">
          <tinymce v-model="productInfo.product.detailMobileHtml" :height="300" />
          <el-row>
            <el-col :span="18" :offset="0">
              <el-form-item label="备注">
                <el-input
                  v-model="productInfo.product.note"
                  type="textarea"
                  :rows="2"
                  placeholder="备注"
                />
              </el-form-item>
            </el-col>
          </el-row>

        </div>
        <el-row>
          <el-col :span="12" :offset="9">
            <el-form-item class="btn">
              <el-button v-if="index == 1" type="primary" @click="goNext">下一步,填写库存信息</el-button>
              <el-button v-if="index == 2 || index == 3" @click="goBack">返回上一步</el-button>
              <el-button v-if="index == 2" type="primary" @click="goNext">下一步,填写移动端详情</el-button>
              <el-button v-if="index == 3" type="primary" @click="onSubmit">提交保存</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>

  </div>
</template>

<script>
import { getAllCategory } from '@/api/commodityManage/cdClassifity/index'
import { findAllBrand } from '@/api/commodityManage/cdList/index'
import { getToken } from '@/utils/myAuth'
import Tinymce from '@/components/Tinymce/index.vue'
import { addProductAndSkus, productSkusDetail, updateProductAndSkus } from '@/api/commodityManage/addProduct/index'
export default {
  name: 'VueAdminTemplateMasterIndex',
  components: {
    Tinymce
  },
  data() {
    return {
      ImgList: [],
      checkList: [],
      colorList: [],
      sizeList: [],
      color: '',
      size: '',
      dialogImageUrl: '',
      dialogVisible: false,
      setToken: {
        token: getToken()
      },
      brandList: [],
      categoryList: [],
      index: 1,
      productInfo: {
        'pmsSkuStockList': [

        ],
        'product': {
          'albumPics': '',
          'brandId': '',
          'brandName': '',
          'createTime': '',
          'deleteStatus': '',
          'description': '',
          'detailDesc': '',
          'detailHtml': '',
          'detailMobileHtml': '',
          'detailTitle': '',
          'feightTemplateId': '',
          'giftGrowth': '',
          'giftPoint': '',
          'id': '',
          'keywords': '',
          'lowStock': '',
          'modifyTime': '',
          'name': '',
          'newStatus': '',
          'note': '',
          'originalPrice': '',
          'pic': '',
          'previewStatus': '',
          'price': '999',
          'productAttributeCategoryId': '',
          'productCategoryId': '',
          'productCategoryName': '',
          'productSn': '',
          'promotionEndTime': '',
          'promotionPerLimit': '',
          'promotionPrice': '',
          'promotionStartTime': '',
          'promotionType': '',
          'publishStatus': '',
          'recommendStatus': '',
          'sale': '',
          'serviceIds': '',
          'sort': '',
          'stock': '',
          'subTitle': '',
          'unit': '',
          'usePointLimit': '',
          'verifyStatus': '',
          'weight': ''
        }
      }
    }
  },

  created() {
    console.log(this.$route.query.productId)
    if (this.$route.query.productId) {
      productSkusDetail(this.$route.query.productId).then(res => {
        res.data.product.recommendStatus = !!res.data.product.recommendStatus
        res.data.product.newStatus = !!res.data.product.newStatus
        res.data.product.previewStatus = !!res.data.product.previewStatus
        res.data.product.verifyStatus = !!res.data.product.verifyStatus
        res.data.product.publishStatus = !!res.data.product.publishStatus
        res.data.product.albumPics.split(',').forEach((ele, index) => {
          this.ImgList.push({ name: index, url: ele })
        })
        this.checkList = res.data.product.serviceIds.split(',')
        var newArr = res.data.skus.map(ele => {
          ele.spData = JSON.parse(ele.spData)
          return ele
        })
        console.log(newArr)
        this.productInfo.pmsSkuStockList = newArr
        this.productInfo.product = res.data.product
      })
    }

    findAllBrand().then(res => {
      this.brandList = res.data.items
      console.log(this.brandList)
    })
    getAllCategory().then(res => {
      this.categoryList = res.data.items.find(ele => {
        return ele.category.name === '乐居'
      }).children
    })
  },

  mounted() {

  },

  methods: {
    delItem(index) {
      this.productInfo.pmsSkuStockList.splice(index, 1)
    },
    addSkuItem() {
      var colorList = this.colorList.filter(ele => ele.isSelect)
      console.log(colorList)
      if (colorList.length !== 0) {
        colorList.forEach(ele => {
          var arr = [{ 'key': '颜色', 'value': ele.name }, { 'key': '容量', 'value': '' }]
          var obj = {
            'createTime': '',
            'id': '',
            'lockStock': '',
            'lowStock': '',
            'modifyTime': '',
            'pic': '',
            'price': '',
            'productId': '',
            'promotionPrice': '',
            'sale': '',
            'skuCode': '',
            'spData': arr,
            'stock': ''
          }
          this.productInfo.pmsSkuStockList.push(obj)
        })
      } else {
        this.$message.error('请选中颜色')
      }
    },
    delSkuColor(index) {
      this.colorList.splice(index, 1)
    },
    delSkuSize(index) {
      this.sizeList.splice(index, 1)
    },
    getCategoryName(e) {
      this.productInfo.productCategoryName = this.categoryList.find(ele => {
        return ele.id === e
      }).name
    },
    getCheckList(e) {
      this.productInfo.product.serviceIds = e.join(',')
    },
    onSubmit() {
      this.productInfo.product.recommendStatus = this.productInfo.product.recommendStatus ? 1 : 0
      this.productInfo.product.newStatus = this.productInfo.product.newStatus ? 1 : 0
      this.productInfo.product.previewStatus = this.productInfo.product.previewStatus ? 1 : 0
      this.productInfo.product.verifyStatus = this.productInfo.product.verifyStatus ? 1 : 0
      this.productInfo.product.publishStatus = this.productInfo.product.publishStatus ? 1 : 0

      this.productInfo.pmsSkuStockList.forEach(ele => {
        ele.spData = JSON.stringify(ele.spData)
        console.log(ele.spData, JSON.stringify(ele.spData))
        console.log(typeof ele.spData)
        console.log(typeof JSON.stringify(ele.spData))
      })

      if (this.$route.query.productId) {
        console.log(this.productInfo)
        updateProductAndSkus(this.productInfo).then(res => {
          this.$router.push('/commodityManage/cdList')
        })
      } else {
        addProductAndSkus(this.productInfo).then(res => {
          this.$router.push('/commodityManage/cdList')
        })
      }
    },
    getBrandName(id) {
      this.productInfo.product.brandName = this.brandList.find(ele => {
        return ele.id === id
      }).name
    },
    addSku() {
      var colorList = this.colorList.filter(ele => ele.isSelect)
      var sizeList = this.sizeList.filter(ele => ele.isSelect)
      var list = []
      colorList.forEach(ele => {
        sizeList.forEach(itm => {
          var arr = [{ 'key': '颜色', 'value': ele.name }, { 'key': '容量', 'value': itm.name }]
          var obj = {
            'createTime': '',
            'id': '',
            'lockStock': '',
            'lowStock': '',
            'modifyTime': '',
            'pic': '',
            'price': '',
            'productId': '',
            'promotionPrice': '',
            'sale': '',
            'skuCode': '',
            'spData': arr,
            'stock': ''
          }
          list.push(obj)
        })
      })
      this.productInfo.pmsSkuStockList = list
    },
    addColor() {
      this.colorList.push({
        name: this.color,
        isSelect: false
      })
      this.color = ''
    },
    addSize() {
      this.sizeList.push({
        name: this.size,
        isSelect: false
      })
      this.size = ''
    },
    upAlbumPics(response, file, fileList) {
      console.log(fileList)
      var arr = []
      fileList.forEach(ele => {
        if (ele.response) {
          arr.push(ele.response.data.fileUrl)
        } else {
          arr.push(ele.url)
        }
      })
      this.productInfo.product.albumPics = arr.join(',')
    },
    handleRemove(file, fileList) {
      console.log(fileList)
      var arr = []
      fileList.forEach(ele => {
        if (ele.response) {
          arr.push(ele.response.data.fileUrl)
        } else {
          arr.push(ele.url)
        }
      })
      this.productInfo.product.albumPics = arr.join(',')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    goNext() {
      this.index++
    },
    goBack() {
      this.index--
    },
    upImg(response) {
      this.productInfo.product.pic = response.data.fileUrl
    },
    upSkuImg(index, response) {
      console.log(index, response)
      this.productInfo.pmsSkuStockList[index].pic = response.data.fileUrl
    }
  }
}
</script>

<style scoped lang="scss">
.product{
  background-color: #f0f2f5;
  .steps{
    background-color: #fff;
    padding-top: 30px;
    height: 120px;
  }
  .form{
    background-color: #fff;
    padding: 20px;
    .title{
      padding: 10px 0px ;
      border-bottom: 1px solid #e5e5e5;
      margin-bottom: 30px;
    }
    .btn{
      margin-top: 30px;
    }
  }
  .center{
    display: flex;
    align-items: center;
  }
}

</style>
